<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文档管理 - RAG 智能问答系统</title>
    
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Material Icons -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" />
    
    <!-- Inter 字体 -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- 自定义样式 -->
    <link rel="stylesheet" href="css/styles.css">
    
    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'accent-blue': '#A7C7ED',
                        'accent-purple': '#D0BCE1',
                        'accent-pink': '#F4B6C2',
                        'bg-primary': '#E8F0FE',
                        'bg-secondary': '#F0F8FF',
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-bg-secondary min-h-screen">
    <!-- 主容器 -->
    <div class="max-w-4xl mx-auto p-4 md:p-8">
        <!-- 顶部导航区 -->
        <div class="flex items-center justify-between mb-8">
            <!-- 返回按钮 -->
            <a href="index.html" class="flex items-center gap-2 px-3 py-2 text-accent-blue hover:bg-accent-blue/10 rounded-md transition">
                <span class="material-symbols-outlined">arrow_back</span>
                <span>返回聊天</span>
            </a>

            <!-- 页面标题 -->
            <h1 class="text-3xl font-bold text-gray-800">文档管理</h1>

            <!-- 占位 -->
            <div class="w-24"></div>
        </div>

        <!-- 上传区域卡片 -->
        <div id="uploadArea" class="bg-white border-2 border-dashed border-accent-blue/50 rounded-xl p-8 shadow-md mb-8 transition-all cursor-pointer hover:border-accent-blue">
            <input type="file" id="fileInput" accept=".txt" class="hidden">
            
            <div class="flex flex-col items-center gap-4">
                <!-- 上传图标 -->
                <div class="text-accent-blue">
                    <span class="material-symbols-outlined" style="font-size: 48px;">cloud_upload</span>
                </div>

                <!-- 提示文字 -->
                <div class="text-center">
                    <p class="text-lg font-medium text-gray-800 mb-2">点击上传或拖拽文件到此处</p>
                    <p class="text-sm text-gray-500">仅支持 .txt 格式，最大 10MB</p>
                </div>

                <!-- 选择文件按钮 -->
                <button id="selectFileBtn" class="bg-accent-blue text-white font-bold px-6 py-3 rounded-full shadow-lg hover:shadow-xl hover:scale-105 transition-all duration-300" style="box-shadow: 0 0 5px rgba(167, 199, 237, 0.5);">
                    选择文件
                </button>

                <!-- 上传进度条 -->
                <div id="uploadProgress" class="w-full max-w-md hidden">
                    <div class="bg-gray-200 rounded-full h-2 overflow-hidden">
                        <div id="progressBar" class="bg-accent-blue h-full transition-all duration-300" style="width: 0%"></div>
                    </div>
                    <p class="text-sm text-gray-600 text-center mt-2">上传中...</p>
                </div>
            </div>
        </div>

        <!-- 文档列表区域 -->
        <div class="mb-6 flex items-center justify-between">
            <h2 class="text-xl font-bold text-gray-800">
                已上传文档 <span id="documentCount" class="text-accent-blue">(共 0 个)</span>
            </h2>
            <button id="refreshBtn" class="p-2 text-gray-600 hover:text-accent-blue hover:bg-accent-blue/10 rounded-lg transition">
                <span class="material-symbols-outlined">refresh</span>
            </button>
        </div>

        <!-- 文档列表 -->
        <div id="documentsList" class="space-y-3">
            <!-- 加载状态 -->
            <div id="loadingState" class="flex items-center justify-center py-12">
                <div class="flex items-center gap-3">
                    <span class="material-symbols-outlined loading-spinner text-accent-blue" style="font-size: 32px;">progress_activity</span>
                    <span class="text-gray-600">加载中...</span>
                </div>
            </div>

            <!-- 空状态 -->
            <div id="emptyState" class="hidden flex flex-col items-center justify-center py-12 text-gray-400">
                <span class="material-symbols-outlined mb-3" style="font-size: 64px;">description</span>
                <p class="text-lg">暂无文档，请先上传</p>
            </div>
        </div>
    </div>

    <!-- 加载 API 工具 -->
    <script src="js/api.js"></script>

    <!-- 页面脚本 -->
    <script>
        // DOM 元素
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const selectFileBtn = document.getElementById('selectFileBtn');
        const uploadProgress = document.getElementById('uploadProgress');
        const progressBar = document.getElementById('progressBar');
        const documentsList = document.getElementById('documentsList');
        const loadingState = document.getElementById('loadingState');
        const emptyState = document.getElementById('emptyState');
        const documentCount = document.getElementById('documentCount');
        const refreshBtn = document.getElementById('refreshBtn');

        let documents = [];

        // 文件选择
        selectFileBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            fileInput.click();
        });

        uploadArea.addEventListener('click', () => {
            fileInput.click();
        });

        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                handleFileUpload(file);
            }
        });

        // 拖拽上传
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('upload-area-drag-over');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('upload-area-drag-over');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('upload-area-drag-over');
            
            const file = e.dataTransfer.files[0];
            if (file) {
                handleFileUpload(file);
            }
        });

        // 处理文件上传
        async function handleFileUpload(file) {
            // 验证文件类型
            if (!file.name.endsWith('.txt')) {
                Toast.show('仅支持 .txt 格式文件', 'error');
                return;
            }

            // 验证文件大小（10MB）
            if (file.size > 10 * 1024 * 1024) {
                Toast.show('文件大小不能超过 10MB', 'error');
                return;
            }

            // 显示进度条
            uploadProgress.classList.remove('hidden');
            progressBar.style.width = '0%';

            // 模拟进度
            let progress = 0;
            const progressInterval = setInterval(() => {
                progress += 10;
                if (progress <= 90) {
                    progressBar.style.width = progress + '%';
                }
            }, 100);

            try {
                const result = await API.uploadDocument(file);
                
                // 完成进度
                clearInterval(progressInterval);
                progressBar.style.width = '100%';

                setTimeout(() => {
                    uploadProgress.classList.add('hidden');
                    Toast.show(`文件上传成功！共分为 ${result.chunks_count || result.chunks || 0} 个文本块`, 'success');
                    
                    // 刷新文档列表
                    loadDocuments();
                    
                    // 重置文件输入
                    fileInput.value = '';
                }, 500);

            } catch (error) {
                clearInterval(progressInterval);
                uploadProgress.classList.add('hidden');
                Toast.show('上传失败: ' + error.message, 'error');
                fileInput.value = '';
            }
        }

        // 加载文档列表
        async function loadDocuments() {
            loadingState.classList.remove('hidden');
            emptyState.classList.add('hidden');
            
            // 清空现有列表
            const existingDocs = documentsList.querySelectorAll('.document-card');
            existingDocs.forEach(doc => doc.remove());

            try {
                const docs = await API.getDocuments();
                documents = docs.documents || docs;

                loadingState.classList.add('hidden');

                if (documents.length === 0) {
                    emptyState.classList.remove('hidden');
                    documentCount.textContent = '(共 0 个)';
                } else {
                    emptyState.classList.add('hidden');
                    documentCount.textContent = `(共 ${documents.length} 个)`;
                    
                    // 渲染文档列表
                    documents.forEach((doc, index) => {
                        setTimeout(() => {
                            createDocumentCard(doc);
                        }, index * 50); // 错开动画
                    });
                }

            } catch (error) {
                loadingState.classList.add('hidden');
                console.error('加载文档列表失败:', error);
                
                // 根据错误类型给出不同提示
                let errorMessage = '加载文档列表失败';
                if (error.message.includes('fetch') || error.message.includes('Failed to fetch')) {
                    errorMessage = '无法连接到后端服务，请确保后端服务正在运行 (http://localhost:8000)';
                } else if (error.message.includes('404')) {
                    errorMessage = 'API接口不存在，请检查后端服务配置';
                }
                
                Toast.show(errorMessage, 'error');
                
                // 显示空状态
                emptyState.classList.remove('hidden');
                documentCount.textContent = '(共 0 个)';
            }
        }

        // 创建文档卡片
        function createDocumentCard(doc) {
            const card = document.createElement('div');
            card.className = 'document-card bg-white border border-accent-blue/20 rounded-lg p-4 shadow-sm hover:shadow-md hover:border-accent-blue/50 transition-all duration-200 message-enter';
            card.dataset.docId = doc.document_id;

            card.innerHTML = `
                <div class="flex items-start gap-3">
                    <!-- 文档图标 -->
                    <div class="text-accent-blue shrink-0">
                        <span class="material-symbols-outlined" style="font-size: 24px;">description</span>
                    </div>

                    <!-- 文档信息 -->
                    <div class="flex-1 min-w-0">
                        <h3 class="font-medium text-gray-800 truncate mb-1">${escapeHtml(doc.filename)}</h3>
                        <div class="flex items-center gap-3 text-sm text-gray-500">
                            <span class="flex items-center gap-1">
                                <span class="material-symbols-outlined" style="font-size: 16px;">schedule</span>
                                ${formatTime(doc.upload_time)}
                            </span>
                            <span>·</span>
                            <span class="flex items-center gap-1">
                                <span class="material-symbols-outlined" style="font-size: 16px;">splitscreen</span>
                                分块数: ${doc.chunks_count || doc.chunks || 0} 块
                            </span>
                        </div>
                    </div>

                    <!-- 删除按钮 -->
                    <button 
                        class="delete-btn p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-md transition shrink-0"
                        data-doc-id="${doc.document_id}"
                        data-filename="${escapeHtml(doc.filename)}"
                    >
                        <span class="material-symbols-outlined">delete</span>
                    </button>
                </div>
            `;

            documentsList.appendChild(card);

            // 绑定删除事件
            const deleteBtn = card.querySelector('.delete-btn');
            deleteBtn.addEventListener('click', () => {
                handleDeleteDocument(doc.document_id, doc.filename, card);
            });
        }

        // 处理删除文档
        function handleDeleteDocument(documentId, filename, cardElement) {
            Modal.confirm(
                '确认删除',
                `确定要删除文档《${filename}》吗？删除后将无法恢复。`,
                async () => {
                    try {
                        // 添加删除动画
                        cardElement.classList.add('file-exit');

                        // 等待动画完成
                        await new Promise(resolve => setTimeout(resolve, 300));

                        // 调用删除API
                        await API.deleteDocument(documentId);

                        // 从DOM中移除
                        cardElement.remove();

                        // 更新文档数量
                        documents = documents.filter(doc => doc.document_id !== documentId);
                        documentCount.textContent = `(共 ${documents.length} 个)`;

                        // 如果没有文档了，显示空状态
                        if (documents.length === 0) {
                            emptyState.classList.remove('hidden');
                        }

                        Toast.show('文档删除成功', 'success');

                    } catch (error) {
                        // 移除动画类，恢复卡片
                        cardElement.classList.remove('file-exit');
                        Toast.show('删除失败: ' + error.message, 'error');
                    }
                }
            );
        }

        // 刷新按钮
        refreshBtn.addEventListener('click', () => {
            Toast.show('正在刷新...', 'info');
            loadDocuments();
        });

        // 页面加载时获取文档列表
        loadDocuments();

        console.log('文档管理页面已启动');
    </script>
</body>
</html>

